<?php

	session_start();

	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {

		// no login, move to index page
		header("Location: http://localhost/atbat/html/");

	}

	// connect to db
	require_once '../db/db.php';

	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";
		
	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];

	// get roster info based on url hash
	if(isset($_GET['id']) && $_GET['id'] != '') {

		$sql = "SELECT * FROM rosters WHERE roster_id = " . $_GET['id'];
		$roster = $db->query($sql)->fetch(PDO::FETCH_ASSOC);

	}else{ // return to main roster page

		header("Location: http://localhost/atbat/html//rosters");

	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Rosters - <?php echo $roster['nickname']; ?></title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css"><link rel="stylesheet" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
    	<h1><?php echo $roster['nickname']; ?></h1>
        <h3><?php echo $roster['team']; ?></h3>
        <!-- 
        	* show roster info and all players associated with in 
           	* built in ability to add and remove players from here 
        -->
        <table id="rosters" cellpadding="0" cellspacing="0" summary="Show the details and all players for this roster">
        	<tr>
            	<th>Player Name</th>
                <th>#</th>
                <th>Position</th>
                <th>Actions</th>
            </tr>
            <?php

				$sql = "SELECT players.player_id, players.number, players.name, positions.code FROM players LEFT JOIN rosters_players ON rosters_players.player_id = players.player_id LEFT JOIN positions ON positions.position_id = players.position WHERE rosters_players.roster_id = " . $roster['roster_id'];

				foreach($db->query($sql) as $p) {

			?>
            <tr id="<?php echo $p['player_id']; ?>" class="player">
            	<td><a href="view-player/<?php echo $p['player_id']; ?>"><?php echo $p['name']; ?></a></td>
                <td><?php echo $p['number']; ?></td>
                <td><?php echo $p['code']; ?></td>
                <td><a href="edit-player/<?php echo $p['player_id']; ?>" title="Use this to change a player from one roster to another">Edit</a> | <a href="remove-player/<?php echo $p['player_id']; ?>" rel="<?php echo $p['name']; ?>" class="remove">Remove from Roster</a> | <a href="delete-player/<?php echo $p['player_id']; ?>" class="delete">Delete</a></td>
            </tr>
            <?php } ?>
            <tr>
            	<form action="roster-add.php" method="post">
                	<td colspan="4">
                    	<label for="player">Add a Player:</label>
                    	<select name="player" id="player" required>
							<option value="">Choose One</option>
                        	<?php

								// list all available players based on user id and 'unsigned' players
								// ability to create a player on the fly and add to roster also
								$sql = "SELECT players.player_id, players.name FROM players LEFT JOIN rosters_players ON players.player_id = rosters_players.player_id WHERE rosters_players.player_id IS NULL OR rosters_players.roster_id != " . $roster['roster_id'];

								foreach ($db->query($sql) as $p) print '<option value="' . $p['player_id'] . '">' . $p['name'] . '</option>';

							?>
                            <option value="">Create a Player</option>
                        </select>
                        <input type="submit" name="add_player" id="add_player" value="Add Player" />
                    </td>
                </form>
            </tr>
        </table>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
    <script>
    	$(document).ready(function() {
			var p_id;
			var p_name;
			
			// add player to roster
			$("#add_player").hide();
			$("#player").change(function() {
				if($("#player").val() != '') {
					$.post(
						"roster-add.php",
						{ 
							id: $(this).val(),
							roster_id: <?php echo $_GET['id']; ?>,
							add2roster: 1
						},
						function(data) {
							if($(data).hasClass('error')) { // show error message
								$(".error").remove();
								$("#add_player").before(data);
							}else{ // add player to roster list
								$(".error").remove();
								$(".player:last").after(data);
							}
						}
					);
				}
			});
			
			// delete player
			$(".delete").click(function() {
				// show delete confirm dialog
				$("#dialog-confirm").dialog("open");
				p_id = $(this).attr("href");
				p_id = p_id.split("/");
				return false;					
			});

			$("#dialog-confirm").dialog({
				resizable: false,
				draggable: false,
				autoOpen: false,
				modal: true,
				buttons: {
					"Delete Player": function() {
						// delete player via ajax
						$.post(
							"delete-player.php",
							{
								id: p_id[1],
								delete_player: true
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialog-confirm").prepend(data);
								if($(data).hasClass('notice')) {
									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialog-confirm").dialog("close"); }, 2500);
									// remove deleted player from table
									$("#" + p_id[1]).fadeOut('slow');
								}
							}
						);
					},
					Cancel: function() {
						$(this).dialog("close");
					}
				}
			});

			// remove a player from this roster
			$(".remove").click(function() {
				// show remove confirm dialog
				$("#dialog-remove").dialog("open");
				p_id = $(this).attr("href");
				p_id = p_id.split("/");
				p_name = $(this).attr("rel");
				return false;
			});

			$("#dialog-remove").dialog({
				resizable: false,
				draggable: false,
				autoOpen: false,
				modal: true,
				buttons: {
					"Remove Player": function() {
						// delete player via ajax
						$.post(
							"remove-player.php",
							{
								id: p_id[1],
								roster: <?php echo $roster['roster_id']; ?>,
								remove_player: true
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialog-remove").prepend(data);
								if($(data).hasClass('success')) {
									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialog-remove").dialog("close"); }, 2500);
									// remove deleted player from table
									$("#" + p_id[1]).fadeOut('slow');
									// add deleted player to drop down input
									$("#player").append('<option value="' + p_id[1] + '">' + p_name + '</option>');
								}
							}
						);
					},
					Cancel: function() {
						$(this).dialog("close");
					}
				}
			});

			// create player on the fly
			$("#player").change(function() {
				if($("#player").val() == '') {
					$("#dialog-create").dialog("open");
				}
			});

			// date picker
			if(!Modernizr.inputtypes.date) {
				$("#dob").datepicker({
					changeMonth: true,
					changeYear: true,
					dateFormat: 'mm/dd/yy',
					yearRange: '1900:2011'
				});
			}

			$("#dialog-create").dialog({
				width: 648,
				resizable: false,
				draggable: false,
				autoOpen: false,
				modal: true,
				buttons: {
					"Create Player": function() {
						$.post(
							"create-player.php",
							{
								first_name: $("#first_name").val(),
								last_name: $("#last_name").val(),
								number: $("#number").val(),
								position: $("#position").val(),
								bats: $("#bats:checked").val(),
								throws: $("#throws:checked").val(),
								feet: $("#feet").val(),
								inches: $("#inches").val(),
								weight: $("#weight").val(),
								dob: $("#dob").val(),
								team: $("#team").val(),
								roster: $("#roster").val(),
								createPlayer: $("#createPlayer").val()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialog-create").prepend(data);
								if($(data).hasClass('success')) {
									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialog-create").dialog("close"); }, 2500);
									// add new player to form element
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$("#player").append('<option value="' + select_id + '" selected>' + select_title + '</option>');
								}
							}
						);
					},
					Cancel: function() {
						$(this).dialog("close");
					}
				}
			});
		});
    </script>
    <div id="dialog-confirm" title="Delete Player">
    	<p>Do you really wish to delete this player?</p>
        <p>Doing so will remove this player from your list of players, remove them from their team &amp; any rosters and delete all of their stats.</p>
    </div>
    <div id="dialog-remove" title="Remove This Player">
    	<p>Do you really want to remove this player from this roster?</p>
    </div>
	<fieldset id="dialog-create" title="Create a New Player">
		<p><label for="first_name">First Name:</label><input type="text" name="first_name" id="first_name" required /></p>
		<p><label for="last_name">Last Name:</label><input type="text" name="last_name" id="last_name" required /></p>
		<p><label for="number">Number:</label><input type="number" name="number" id="number" min="0" max="99" step="1" required /></p>
		<p>
			<label for="position">Position:</label>
			<select name="position" id="position" required>
				<?php

					foreach($db->query("SELECT position_id, title FROM positions") as $p) {

						print '<option value="' . $p[0] . '">' . $p[1] . '</option>';

					}

				?>
			</select>
		</p>
		<p><label>Bats:</label></p>
		<p class="radio"><input type="radio" name="bats" id="bats_l" value="L" /><label for="bats_l">Left</label></p>
		<p class="radio"><input type="radio" name="bats" id="bats_r" value="R" /><label for="bats_r">Right</label></p>
		<p class="radio"><input type="radio" name="bats" id="bats_s" value="S" /><label for="bats_s">Switch</label></p>
		<p><label>Throws:</label></p>
		<p class="radio"><input type="radio" name="throws" id="throws_l" value="L" /><label for="throws_l">Left</label></p>
		<p class="radio"><input type="radio" name="throws" id="throws_r" value="R" /><label for="throws_r">Right</label></p>
		<p><label for="feet">Height:</label><input type="number" min="3" max="7" step="1" name="feet" id="feet" />' - <input type="number" min="0" max="11" step="1" name="inches" id="inches" />"</p>
		<p><label for="weight">Weight:</label><input type="number" min="0" max="400" step="1" name="weight" id="weight" />lbs.</p>
		<p><label for="dob">Date of Birth:</label><input type="date" name="dob" id="dob" placeholder="MM-DD-YYYY" /></p>
		<p>
			<label for="team">Team:</label>
			<select name="team" id="team" required>
				<option value="0">Choose One</option>
				<?php

					foreach($db->query("SELECT team_id, city, name FROM teams WHERE user_id IN (0, " . $user_id . ")") as $t) {

						print '<option value="' . $t['team_id'] . '">' . $t['city'] . ' ' . $t['name'] . '</option>';

					}

				?>
			</select>    
		</p>
		<input type="hidden" name="roster" id="roster" value="<?php echo $roster['roster_id']; ?>" />
		<input type="hidden" name="createPlayer" id="createPlayer" value="1" />
	</fieldset>
</body>
</html>